<?php
/**
 * Created by PhpStorm.
 * User: YONBIN
 * Date: 2020/11/25
 * Time: 10:43
 * Email: 479703456@qq.com
 */

namespace app\domain\admin;


use app\model\Admin;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class LoginDomain extends CommonDomain
{
    public function login($username, $password)
    {
        try {
            $info = app(Admin::class)->getByUsername($username);
            if (!$info) {
                $this->errMsg = '用户不存在';
                return false;
            }

            if (true !== $info->checkPassword($password)) {
                $this->errMsg = 'login.account_not_match';
                return false;
            }

            $payload = [
                'module' => 'admin',
                'groupId' => $info->group_id,
                'userId' => $info->id,
                'expire' => time() + env('jwt.admin_expire')
            ];

            $authorization = JWT::encode($payload, env('jwt.admin_key'), 'HS256');

            return [
                'authorization' => $authorization,
                'userinfo' => [
                    'id' => $info->id,
                    'group_id' => $info->group_id,
                    'username' => $info->username,
                ],
                //'userInfo' => $info,
            ];
        } catch (\Exception $e) {
            $this->errMsg = $e->getMessage();
            return [];
        }
    }

    public function getUserInfo()
    {
        try {
            $authorization = request()->header('authorization');
            if (!$authorization) {
                $this->errMsg = '请先登录';
                return false;
            }

            $payload = (array)JWT::decode($authorization, new Key(env('jwt.admin_key'), 'HS256'));
            $info = app(Admin::class)->withoutField(['password', 'salt'])->where(['id' => $payload['userId']])->find();
            if (!$info) {
                $this->errMsg = '用户不存在';
                return false;
            }
            return [
                'info' => $info,
                'roles' => [
                    [
                        'roleName' => 'admin',
                        'value' => 'admin',
                    ]
                ],
            ];
        } catch (\Exception $e) {
            $this->errMsg = '请先登录:' . $e->getMessage();
            return false;
        }
    }

    public function logout()
    {
        return true;
    }
}